package com.ee.bruscar.util.reflection;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ee.bruscar.exceptions.BruscarException;

public class TypeChecker
{
	
	public static String getSetterName(String fieldName)
	{
		return "set" + capitalize( fieldName );
	}
	
	private static String capitalize( String value )
	{
		String firstLetter = value.substring(0,1);
		String remainder = value.substring(1);
		return firstLetter.toUpperCase() + remainder;
	}

	
	public static List<Method> getSetters( Class<?> clazz )
	{
		List<Method> settersList = new ArrayList<Method>();
		
		for( int i = 0 ; i < clazz.getMethods().length ; i++ )
		{
			Method method = clazz.getMethods()[i];
			if( method.getName().startsWith("set") && method.getName().length() > 3)
			{
				settersList.add( method );
			}
		}
		return settersList;
	}

	public static boolean isCustomType( Class<?> clazz )
	{
		return !isPrimitive( clazz );
	}
	
    public static boolean isPrimitive( Class<?> type )
    {
        if( type.getName().equals("boolean"))
        {
            return true;
        }
        if( type.getName().equals("int"))
        {
            return true;
        }
        if( type.getName().equals("long"))
        {
            return true;
        }
        if( type.getName().equals("double"))
        {
            return true;
        }
        if( type == java.lang.annotation.Annotation.class )
        {
            return true;
        }
        if( type == String.class )
        {
            return true;
        }
        if( type == Integer.class )
        {
            return true;
        }
        if( type == Boolean.class )
        {
            return true;
        }
        if( type == Date.class )
        {
            return true;
        }
        return false;
    }

	public static String getFieldName(String name)
	{
		if( name.startsWith("set"))
		{
			name = name.substring(3);
			return lowercaseFirstLetter( name );
		}
		else if( name.startsWith("is"))
		{
			name = name.substring(2);
			return lowercaseFirstLetter( name );
		}
		throw new BruscarException("is this a setter? : " + name );
	}

	private static String lowercaseFirstLetter(String name)
	{
		String firstLetter = name.substring(0,1);
		String remainder = name.substring(1);
		return firstLetter.toLowerCase() + remainder;
	}

	public static boolean isList(Class<?> clazz)
	{
		if( clazz.equals(List.class))
		{
			return true;
		}
		Class<?>[] classes = clazz.getClasses();
		for( int i = 0 ; i < classes.length ; i++ )
		{
			Class<?> supportedClass = classes[i];
			if( supportedClass.equals( List.class ))
			{
				return true;
			}
		}	
		
		return false;
	}
}
